package ch.uzh.ifi.seal.ssqa.util;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.resources.IFile;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.gmf.runtime.emf.core.resources.GMFResource;

import ch.uzh.ifi.seal.ssqa.model.Diagram;
import ch.uzh.ifi.seal.ssqa.model.DiagramComponent;
import ch.uzh.ifi.seal.ssqa.model.DiagramComposite;

public class DiagramComponentProvider {
	
	private List<DiagramComponent> components = new ArrayList<DiagramComponent>();
	
	public DiagramComponentProvider(IFile file){
		ResourceSet resSet = new ResourceSetImpl();           
		GMFResource resource = (GMFResource) resSet.getResource(URI.createPlatformResourceURI(file.getFullPath().toString(), false), true);  
		for(EObject object : resource.getContents()){
			if(object instanceof Diagram){
				for(DiagramComponent component : ((Diagram)object).getComponents()){
					if(component instanceof DiagramComposite){
						this.getChildren((DiagramComposite)component);
					} else {
						this.components.add(component);
					}
				}
			}
		}
	}
	
	public DiagramComponentProvider(Diagram diagram){
		for(DiagramComponent component : diagram.getComponents()){
			if(component instanceof DiagramComposite){
				this.getChildren((DiagramComposite)component);
			} else {
				this.components.add(component);
			}
		}
	}
	
	public List<DiagramComponent> getDiagramComponents(){
		return this.components;
	}
	
	private void getChildren(DiagramComposite composite){
		this.components.add(composite);
		if(!composite.getChildren().isEmpty()){
			for(DiagramComponent component : composite.getChildren()){
				if(component instanceof DiagramComposite){
					this.getChildren((DiagramComposite)component);
				} else {
					this.components.add(component);
				}
			}
		}
	}
}
